package com.hy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.entity.Exchange;
import com.hy.entity.Product;
import com.hy.entity.User;
import com.hy.mapper.ExchangeMapper;
import com.hy.mapper.ProductMapper;
import com.hy.service.ExchangeService;
import com.hy.service.ProductService;
import com.hy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ExchangeServiceImpl extends ServiceImpl<ExchangeMapper, Exchange> implements ExchangeService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public boolean create(Long userId, Long productId, String address) {
        // 获取商品信息
        Product product = productMapper.selectById(productId);
        if (product == null || product.getStatus() != 1 || product.getStock() <= 0) {
            return false;
        }
        
        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null || user.getPoints() < product.getPoints()) {
            return false;
        }
        
        // 扣减积分
        if (!userService.reducePoints(userId, product.getPoints())) {
            return false;
        }
        
        // 减少库存
        product.setStock(product.getStock() - 1);
        if (productMapper.updateById(product) == 0) {
            throw new RuntimeException("更新库存失败");
        }
        
        // 创建兑换记录
        Exchange exchange = new Exchange();
        exchange.setUserId(userId);
        exchange.setProductId(productId);
        exchange.setPoints(product.getPoints());
        exchange.setStatus(0);
        exchange.setAddress(address);
        exchange.setCreateTime(LocalDateTime.now());
        exchange.setUpdateTime(LocalDateTime.now());
        
        return save(exchange);
    }
    
    @Override
    public Page<Exchange> getUserExchanges(Long userId, Integer current, Integer size) {
        Page<Exchange> page = new Page<>(current, size);
        LambdaQueryWrapper<Exchange> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Exchange::getUserId, userId);
        wrapper.orderByDesc(Exchange::getCreateTime);
        return page(page, wrapper);
    }
    
    @Override
    @Transactional
    public boolean cancel(Long id, Long userId) {
        // 获取兑换记录
        LambdaQueryWrapper<Exchange> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Exchange::getId, id);
        wrapper.eq(Exchange::getUserId, userId);
        wrapper.eq(Exchange::getStatus, 0); // 只能取消待处理的订单
        
        Exchange exchange = getOne(wrapper);
        if (exchange == null) {
            return false;
        }
        
        // 更新状态为已取消
        exchange.setStatus(2);
        exchange.setUpdateTime(LocalDateTime.now());
        if (!updateById(exchange)) {
            return false;
        }
        
        // 恢复积分
        if (!userService.addPoints(userId, exchange.getPoints())) {
            throw new RuntimeException("恢复积分失败");
        }
        
        // 恢复库存
        Product product = productMapper.selectById(exchange.getProductId());
        if (product != null) {
            product.setStock(product.getStock() + 1);
            if (productMapper.updateById(product) == 0) {
                throw new RuntimeException("恢复库存失败");
            }
        }
        
        return true;
    }
} 